import {
  ModalForm,
  ProForm,
  ProFormCaptcha,
  ProFormGroup,
  ProFormSelect,
  ProFormSwitch,
} from '@/components/Pro/';
import Tabs, { TabsProps } from '@/components/Tabs';
import { authControllerSendSmsCode } from '@/services/auth/auth';
import { stationControllerGetStation as getDetail } from '@/services/ess/station';
import { stationAreaControllerImplListStationArea } from '@/services/ess/stationArea';
import {
  strategyControllerImplShowTimedStrategy,
  strategyControllerImplUpdateTimedStrategy,
  strategyControllerImplUpdateTimedStrategyEnabled,
} from '@/services/ess/strategy';
import { sysUserControllerGetUserRealPhone } from '@/services/ess/sysUser';
import { MailTwoTone } from '@ant-design/icons';
import { Button, Flex, message, Spin } from 'antd';
import CryptoJS from 'crypto-js/crypto-js';
import JSEncrypt from 'jsencrypt';
import React, {
  forwardRef,
  lazy,
  Suspense,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import { useIntl, useModel } from 'umi';
import GridSwitch from './components/GridSwitch';
import { AESKey, RESKey } from './encryptKey';
import styles from './index.less';

// 初始化
const keyPair = new JSEncrypt();

/**
 * AES加密
 * @param content
 * @returns {string}
 * @constructor
 */
const AESEncryption = (content: string) => {
  const aesContent = CryptoJS.enc.Utf8.parse(content);
  const key = CryptoJS.enc.Utf8.parse(AESKey.key);
  const iv = CryptoJS.enc.Utf8.parse(AESKey.iv);
  const encrypted = CryptoJS.AES.encrypt(aesContent, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
};

/**
 *RSA加密
 * @returns
 */
const encryptByRsa = (content: string) => {
  keyPair.setPublicKey(RESKey);
  return keyPair.encrypt(AESEncryption(content));
};

// 懒加载组件
const TimeSettings = lazy(() => import('./components/TimeSettings'));
const DemandControl = lazy(() => import('./components/DemandControl'));
const History = lazy(() => import('./components/History'));

const BaseInfo = forwardRef((props, ref) => {
  const [form] = ProForm.useForm();
  const [strategyData, setStrategyData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);
  const [smsModalVisible, setSmsModalVisible] = useState(false);
  const [isCaptchaReady, setIsCaptchaReady] = useState(false);
  const [stationAreas, setStationAreas] = useState<{ label: string; value: number }[]>([]);
  const timeSettingsRef = useRef(null);
  const demandControlRef = useRef(null);
  const { isArea } = useModel('@@initialState')?.initialState || {};
  const [userPhone, setUserPhone] = useState<string | null>(null);
  const { initialState } = useModel('@@initialState');
  const intl = useIntl();
  const userId = initialState?.userId;
  const stationId = initialState?.stationId;
  const [strategyEnabled, setStrategyEnabled] = useState(false);
  const [currentOperation, setCurrentOperation] = useState<'status' | 'dispatch'>('dispatch');
  const [detailInfo, setDetailInfo] = useState<API.StationInfo | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const gettingCaptchaRef = useRef(false);
  const [isGettingCaptcha, setIsGettingCaptcha] = useState(false);
  const messageQueue = useRef<boolean>(false);

  const showMessage = (type: 'success' | 'error', content: string) => {
    if (messageQueue.current) return;
    messageQueue.current = true;
    message.destroy();
    if (type === 'success') {
      message.success(content);
    } else {
      message.error(content);
    }
    setTimeout(() => {
      messageQueue.current = false;
    }, 300);
  };

  useEffect(() => {
    if (stationId) {
      getDetail({ id: stationId }).then((res) => {
        if (res?.data) {
          setDetailInfo(res.data);
        } else {
          setDetailInfo(null);
        }
      });
    }
  }, [stationId]);

  console.log('stationId---', detailInfo?.isGridState);

  useEffect(() => {
    const fetchStationAreas = async () => {
      try {
        const response = await stationAreaControllerImplListStationArea();
        if (response.success && response.data) {
          const areas = response.data.map((area) => ({
            label: area.areaName,
            value: area.id,
          }));
          setStationAreas(areas);
        }
      } catch (error) {
        console.error('Failed to fetch station areas:', error);
        message.error(intl.formatMessage({ id: 'strategyAction.error.getStationAreaListFailed' }));
      }
    };

    if (isArea) {
      fetchStationAreas();
    }
  }, [isArea]);

  const fetchStrategyDataRef = useRef<boolean>(false);
  const fetchStrategyData = async (areaId?: number) => {
    if (fetchStrategyDataRef.current) {
      return;
    }

    try {
      fetchStrategyDataRef.current = true;
      setLoading(true);
      console.log('Fetching strategy data for areaId:', areaId);

      const headers: { [key: string]: string } = {};
      if (isArea && areaId) {
        headers['Station-Area'] = areaId.toString();
      }

      const response = await strategyControllerImplShowTimedStrategy({
        headers,
      });

      if (response.code === 200 && response.success && response.data) {
        setStrategyData(response.data);
        setStrategyEnabled(response.data.enabled || false);
      } else {
        console.error('API returned error:', response);
        setStrategyData(null);
      }
    } catch (error) {
      console.error('获取策略数据失败:', error);
      setStrategyData(null);
    } finally {
      setLoading(false);
      setTimeout(() => {
        fetchStrategyDataRef.current = false;
      }, 3000);
    }
  };

  const fetchUserRealPhone = async () => {
    try {
      if (!userId) {
        message.error(intl.formatMessage({ id: 'strategyAction.error.unableToGetUserId' }));
        return;
      }

      const response = await sysUserControllerGetUserRealPhone({ userId });

      if (response.success && response.data) {
        // 使用 RSA 加密手机号
        const encryptedPhone = encryptByRsa(response.data);
        setUserPhone(encryptedPhone);
      } else {
        message.error(
          response.message ||
            intl.formatMessage({ id: 'strategyAction.error.unableToGetUserPhone' }),
        );
      }
    } catch (error) {
      console.error('获取用户手机号失败:', error);
      message.error(intl.formatMessage({ id: 'strategyAction.error.unableToGetUserPhone' }));
    }
  };

  useEffect(() => {
    const init = async () => {
      await fetchStrategyData();
      await fetchUserRealPhone();
    };
    init();
  }, []);

  const handleAreaChange = (areaId: number) => {
    const currentAreaId = form.getFieldValue('area');
    if (currentAreaId !== areaId) {
      fetchStrategyData(areaId || undefined);
    }
  };

  const handleSaveAndDispatch = async () => {
    try {
      await form.validateFields();

      if (!userPhone) {
        await fetchUserRealPhone();
      }

      if (!userPhone) {
        message.error(intl.formatMessage({ id: 'strategyAction.error.unableToGetUserPhone' }));
        return;
      }

      setCurrentOperation('dispatch');
      setConfirmModalVisible(true);
    } catch (errorInfo) {
      console.log('验证失败:', errorInfo);
    }
  };

  const handleConfirm = async () => {
    setConfirmModalVisible(false);
    setSmsModalVisible(true);
    return true;
  };

  const [submitting, setSubmitting] = useState(false);

  const handleDispatchStrategy = async (values: { verificationCode: string }) => {
    // 防止重复提交
    if (submitting) return false;

    try {
      setSubmitting(true);
      const formValues = await form.validateFields();
      const areaId = formValues.area || 0;

      if (!strategyData) {
        await fetchStrategyData(areaId);
      }

      const requestData = {
        stationId: 0,
        areaId: areaId,
        enabled: strategyEnabled,
        demandCtrl:
          demandControlRef.current?.getDemandControlData() || strategyData?.demandCtrl || null,
        strategyType: 1,
        timedStrategy:
          timeSettingsRef.current?.getTimeStrategyData() || strategyData?.timedStrategy || null,
      };

      const response = await strategyControllerImplUpdateTimedStrategy(requestData, {
        headers: {
          'Verification-Code': values.verificationCode,
          'Station-Area': areaId ? areaId.toString() : null,
        },
      }).finally(() => {
        setSubmitting(false);
      });

      // 使用单一的消息处理逻辑
      if (response.success) {
        message.destroy(); // 清除可能存在的消息
        message.success(intl.formatMessage({ id: 'strategyAction.error.strategySendSuccess' }));
        return true;
      } else {
        message.destroy(); // 清除可能存在的消息
        message.error(response.message);
        return false;
      }
    } catch (error) {
      message.destroy(); // 清除可能存在的消息
      message.error(intl.formatMessage({ id: 'strategyAction.error.strategySendFailed' }));
      setSubmitting(false);
      return false;
    }
  };

  const handleStrategyStatusVerify = async (values: { smsCode: string }) => {
    if (submitting) return false;

    try {
      setSubmitting(true);
      const areaId = form.getFieldValue('area') || 0;

      const response = await strategyControllerImplUpdateTimedStrategyEnabled(
        {
          id: strategyData?.id,
          enabled: strategyEnabled,
        },
        {
          headers: {
            'Verification-Code': values.smsCode,
            'Station-Area': areaId ? areaId.toString() : null,
            'Station-Id': stationId ? stationId.toString() : null,
          },
        },
      );

      if (response.success) {
        message.success(intl.formatMessage({ id: 'strategyAction.settings.statusUpdateSuccess' }));
        setSmsModalVisible(false);
        setIsCaptchaReady(false);
        return true;
      } else {
        message.error(response.message);
        setStrategyEnabled(!strategyEnabled);
        return false;
      }
    } catch (error) {
      console.error('更新策略状态失败:', error);
      message.error(intl.formatMessage({ id: 'strategyAction.error.statusUpdateFailed' }));
      setStrategyEnabled(!strategyEnabled);
      return false;
    } finally {
      setSubmitting(false);
    }
  };

  const handleSmsVerify = async (values: { smsCode: string }) => {
    try {
      if (!isCaptchaReady) {
        message.error(intl.formatMessage({ id: 'strategyAction.error.pleaseGetVerificationCode' }));
        return false;
      }

      if (currentOperation === 'status') {
        return handleStrategyStatusVerify(values);
      } else {
        const formValues = await form.validateFields();
        return handleDispatchStrategy({
          ...formValues,
          verificationCode: values.smsCode,
        });
      }
    } catch (error) {
      message.error(intl.formatMessage({ id: 'strategyAction.error.verificationFailed' }));
      return false;
    }
  };

  const handleGetCaptcha = async () => {
    if (gettingCaptchaRef.current) {
      return false;
    }

    try {
      gettingCaptchaRef.current = true;
      setIsGettingCaptcha(true);

      if (!userPhone) {
        await fetchUserRealPhone();
      }

      if (!userPhone) {
        showMessage(
          'error',
          intl.formatMessage({ id: 'strategyAction.error.unableToGetUserPhone' }),
        );
        return false;
      }

      const response = await authControllerSendSmsCode({
        mobile: userPhone,
        smsType: 'issuance_strategy',
      });

      if (response.success) {
        showMessage(
          'success',
          intl.formatMessage({ id: 'strategyAction.error.verificationCodeSentSuccessfully' }),
        );
        setIsCaptchaReady(true);
        return true;
      }

      showMessage(
        'error',
        response.message ||
          intl.formatMessage({ id: 'strategyAction.error.verificationCodeSendFailed' }),
      );
      return false;
    } catch (error) {
      showMessage(
        'error',
        intl.formatMessage({ id: 'strategyAction.error.verificationCodeSendFailed' }),
      );
      return false;
    } finally {
      // 延迟重置状态，避免快速重复点击
      setTimeout(() => {
        gettingCaptchaRef.current = false;
        setIsGettingCaptcha(false);
      }, 300);
    }
  };

  const handleStrategyStatusChange = async (checked: boolean) => {
    // 如果在处理中，直接返回并恢复开关状态
    if (isProcessing) {
      setStrategyEnabled(!checked);
      return;
    }

    try {
      setIsProcessing(true); // 开始处理

      if (!userPhone) {
        await fetchUserRealPhone();
      }

      if (!userPhone) {
        message.destroy(); // 清除之前的消息
        message.error(intl.formatMessage({ id: 'strategyAction.error.unableToGetUserPhone' }));
        setStrategyEnabled(!checked);
        return;
      }

      setStrategyEnabled(checked);
      setCurrentOperation('status');
      setSmsModalVisible(true);
    } catch (error) {
      console.error('处理策略状态变更失败:', error);
      message.destroy(); // 清除之前的消息
      message.error(intl.formatMessage({ id: 'strategyAction.error.statusUpdateFailed' }));
      setStrategyEnabled(!checked);
    } finally {
      // 设置一个短暂的延时，防止快速重复点击
      setTimeout(() => {
        setIsProcessing(false);
      }, 500);
    }
  };

  const refreshData = async () => {
    setLoading(true);
    try {
      // Refresh station details
      if (stationId) {
        const res = await getDetail({ id: stationId });
        if (res?.data) {
          setDetailInfo(res.data);
        } else {
          setDetailInfo(null);
        }
      }

      // Refresh strategy data
      const areaId = form.getFieldValue('area');
      await fetchStrategyData(areaId);

      // Refresh user phone
      await fetchUserRealPhone();
    } catch (error) {
      console.error('Failed to refresh data:', error);
      message.error(intl.formatMessage({ id: 'strategyAction.error.refreshDataFailed' }));
    } finally {
      setLoading(false);
    }
  };

  useImperativeHandle(ref, () => ({
    refreshData,
  }));

  if (loading) {
    return (
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '200px',
        }}
      >
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  return (
    <div className={styles.baseInfo}>
      <ProForm form={form} submitter={false} layout="horizontal">
        <ProFormSwitch
          name="strategyEnabled"
          label={intl.formatMessage({ id: 'strategyAction.settings.strategyStatus' })}
          checkedChildren={intl.formatMessage({ id: 'strategyAction.settings.enabled' })}
          unCheckedChildren={intl.formatMessage({ id: 'strategyAction.settings.disabled' })}
          fieldProps={{
            checked: strategyEnabled,
            onChange: handleStrategyStatusChange,
          }}
        />
        <ProFormGroup>
          <ProFormSelect
            name="area"
            label={intl.formatMessage({ id: 'strategyAction.settings.dimension' })}
            placeholder={
              !isArea
                ? intl.formatMessage({ id: 'strategyAction.settings.wholeStation' })
                : intl.formatMessage({ id: 'strategyAction.settings.pleaseSelect' })
            }
            rules={[
              {
                required: false,
                message: intl.formatMessage({ id: 'strategyAction.settings.pleaseSelect' }),
              },
            ]}
            width={200}
            options={stationAreas}
            disabled={!isArea}
            fieldProps={{
              style: {
                cursor: !isArea ? 'not-allowed' : 'default',
              },
              onChange: handleAreaChange,
            }}
          />
          <ProForm.Item>
            <Button type="primary" onClick={handleSaveAndDispatch}>
              {intl.formatMessage({ id: 'strategyAction.settings.saveAndDispatch' })}
            </Button>
          </ProForm.Item>
        </ProFormGroup>
      </ProForm>
      <div className={styles.grayBar}></div>
      <Suspense fallback={<div>加载中...</div>}>
        <Tabs
          size="middle"
          items={[
            {
              key: 'timeSettings',
              label: intl.formatMessage({ id: 'strategyAction.settings.timeSettings' }),
              children: (
                <TimeSettings
                  ref={timeSettingsRef}
                  strategyData={strategyData}
                  currentAreaId={form.getFieldValue('area')}
                />
              ),
            },
            {
              key: 'demandControl',
              label: intl.formatMessage({ id: 'strategyAction.settings.demandControl' }),
              children: (
                <DemandControl
                  ref={demandControlRef}
                  initialData={strategyData?.demandCtrl}
                  currentAreaId={form.getFieldValue('area')}
                />
              ),
            },
          ]}
        />
      </Suspense>

      <ModalForm
        title={intl.formatMessage({ id: 'strategyAction.settings.prompt' })}
        open={confirmModalVisible}
        onOpenChange={setConfirmModalVisible}
        onFinish={handleConfirm}
        submitTimeout={2000}
        modalProps={{ destroyOnClose: true, bodyStyle: { textAlign: 'center' } }}
        width={420}
        submitter={{
          searchConfig: {
            submitText: intl.formatMessage({ id: 'strategyAction.actions.confirm' }),
            resetText: intl.formatMessage({ id: 'strategyAction.actions.cancel' }),
          },
        }}
      >
        <p style={{ textAlign: 'center', width: '100%', fontSize: '16px' }}>
          {intl.formatMessage({ id: 'strategyAction.settings.confirmStartStrategy' })}
        </p>
      </ModalForm>

      <ModalForm
        title={intl.formatMessage({ id: 'strategyAction.settings.smsVerification' })}
        open={smsModalVisible}
        onOpenChange={setSmsModalVisible}
        onFinish={handleSmsVerify}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            message.destroy(); // 清除所有消息
            if (currentOperation === 'status') {
              setStrategyEnabled(!strategyEnabled);
            }
            setSmsModalVisible(false);
            setIsCaptchaReady(false);
            setCurrentOperation('dispatch');
            setIsProcessing(false); // 重置处理状态
          },
        }}
        width={420}
        submitter={{
          searchConfig: {
            submitText: intl.formatMessage({ id: 'strategyAction.actions.confirm' }),
            resetText: intl.formatMessage({ id: 'strategyAction.actions.cancel' }),
          },
        }}
      >
        <Flex vertical align="center" flex={1}>
          <p>
            {intl.formatMessage({
              id: 'strategyAction.settings.dispatchStrategyRequiresSMSVerification',
            })}
          </p>
          <ProForm.Group>
            <ProFormCaptcha
              fieldProps={{
                size: 'middle',
                prefix: <MailTwoTone />,
              }}
              captchaProps={{
                size: 'middle',
                style: { width: 100, fontSize: 12 },
                loading: isGettingCaptcha,
                disabled: isGettingCaptcha || messageQueue.current,
              }}
              name="smsCode"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'strategyAction.settings.pleaseEnterVerificationCode',
                  }),
                },
              ]}
              placeholder={intl.formatMessage({
                id: 'strategyAction.settings.pleaseEnterVerificationCode',
              })}
              onGetCaptcha={async () => {
                if (gettingCaptchaRef.current || messageQueue.current) {
                  return Promise.reject();
                }
                const success = await handleGetCaptcha();
                if (!success) {
                  return Promise.reject();
                }
                return Promise.resolve();
              }}
            />
          </ProForm.Group>
        </Flex>
      </ModalForm>
    </div>
  );
});

const ParamConfig: React.FC = () => {
  const baseInfoConfRef = useRef(null);
  const [activeKey, setActiveKey] = useState('1');
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const [detailInfo, setDetailInfo] = useState<API.StationInfo | null>(null);
  const stationId = initialState?.stationId;

  // Add a function to fetch station details
  const fetchStationDetails = async () => {
    if (stationId) {
      try {
        const res = await getDetail({ id: stationId });
        if (res?.data) {
          setDetailInfo(res.data);
        } else {
          setDetailInfo(null);
        }
      } catch (error) {
        console.error('Failed to fetch station details:', error);
        message.error(intl.formatMessage({ id: 'strategyAction.error.getStationDetailsFailed' }));
      }
    }
  };

  // Initial data fetch
  useEffect(() => {
    fetchStationDetails();
  }, [stationId]);

  const handleTabChange = async (key: string) => {
    // Refresh data when switching tabs
    await fetchStationDetails();

    // Force refresh BaseInfo component when switching back to tab '1'
    if (key === '1' && baseInfoConfRef.current) {
      // @ts-ignore - Add method to refresh data in BaseInfo
      baseInfoConfRef.current.refreshData?.();
    }

    setActiveKey(key);
  };

  // 根据 isGridState 动态生成 items
  const getTabItems = (isGridState?: boolean): TabsProps['items'] => {
    const baseItems = [
      {
        key: '1',
        label: intl.formatMessage({
          id: 'strategyControl.temporalStrategy.peakArbitrage',
        }),
        children: <BaseInfo ref={baseInfoConfRef} />,
      },
      {
        key: '3',
        label: intl.formatMessage({
          id: 'strategyControl.temporalStrategy.history',
        }),
        children: <History />,
      },
    ];

    // 只有当 isGridState 为 true 时，才添加并离网 tab
    if (isGridState) {
      baseItems.splice(1, 0, {
        key: '2',
        label: intl.formatMessage({
          id: 'strategyControl.temporalStrategy.gridSwitch',
        }),
        children: <GridSwitch />,
      });
    }

    return baseItems;
  };

  return (
    <div>
      <Tabs
        activeKey={activeKey}
        items={getTabItems(detailInfo?.isGridState)}
        onChange={handleTabChange}
      />
    </div>
  );
};

export default ParamConfig;
